package cn.kz.hrm.controller;

import cn.kz.hrm.util.AjaxResult;
import cn.kz.hrm.util.FastDfsApiOpr;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

/**
 * 文件的上传和删除。
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDFSController {

    @RequestMapping("/upload")
    public AjaxResult uploadFile(@RequestBody MultipartFile file){
        try {
            //获取文件的类型。
            String originalFilename = file.getOriginalFilename();
            //获取jpg,这样的后缀名，对文件进行切割。
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用方法对文件的上传保存。
            String upload = FastDfsApiOpr.upload(file.getBytes(), extName);
            //System.out.println(upload);
            //对保存后的路径进行返回。
            return AjaxResult.me().setResultObj(upload);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败！【"+e.getMessage()+"】");
        }
    }

    @RequestMapping("/delete")
    public AjaxResult deleteFile(@RequestParam("filePath") String filePath){
        //对文件的路径进行分割“/”
     //   /group1/M00/00/2E/wKgABF75lDOALgiCAAA5T5Qv51I275.jpg
        try {//  /group1/M00/00/2E/wKgABF75lWSAPj4IAAA5T5Qv51I929.jpg
            String[] strings = filePath.split("/");
            System.out.println(Arrays.toString(strings));
        /*
            //groupName组名:group1
            //fileName文件名:M00/00/0E/wKgABF7cdaqASBpxAAt5AgfM_Pw301.png
            //fileName文件名:M00/00/0E/wKgABF7cdaqASBpxAAt5AgfM_Pw301.png
            // [{"path":", group1, M00, 00, 2E, wKgABF75oMCAHK0kAAA5T5Qv51I523.jpg"}]
         */

            FastDfsApiOpr.delete(strings[1],strings[2] + "/" + strings[3] + "/" + strings[4] + "/" + strings[5]);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件删除失败！【"+e.getMessage()+"】");
        }
    }
}
